package dao

import (
	"git.supremind.info/product/box/vehicle/common"
	"git.supremind.info/product/box/vehicle/global"
	"git.supremind.info/product/box/vehicle/internal/util"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"io/fs"
	"io/ioutil"
	"sort"
	"strings"
)

var DB *gorm.DB

func InitSqlite() {
	common.Logger.Info("初始化数据库连接")

	dbUrl := global.DBPath + "?_busy_timeout=9999999"
	common.Logger.Infof("dbUrl:%v", dbUrl)

	dbConfig := &gorm.Config{}
	if global.Env == "dev" {
		dbConfig = &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}
	}

	db, err := gorm.Open(sqlite.Open(dbUrl), dbConfig)
	if err != nil {
		common.Logger.Fatalf("open config db failed, err: %v", err)
	}
	DB = db

	common.Logger.Info("初始化数据库连接成功")

	// 自动生成表
	DB.AutoMigrate(&UpgradeLog{}, &UpgradeDeb{})
}

func needMigration() {
	var folder = global.DatabaseSetting.UpgradeFolder
	files, err := ioutil.ReadDir(folder)
	if err != nil {
		util.Log().Error("ReadDir[%s],%s", folder, err)
		return
	}
	if files == nil || len(files) == 0 {
		util.Log().Info("no upgrade file......")
		return
	}
	var fileList []fs.FileInfo
	version := getSchemaHistoryVersion()
	for _, file := range files {
		fileNameOnly := util.FileNameWithOutExt(file.Name())
		if strings.Compare(fileNameOnly, version) > 0 {
			fileList = append(fileList, file)
		}
	}

	if fileList == nil || len(fileList) == 0 {
		util.Log().Info("no upgrade file......")
		return
	}

	sort.Sort(util.ByFileName(fileList))
	for _, file := range fileList {
		buf, err := util.ReadFile(folder + "/" + file.Name())
		if err != nil {
			continue
		} else {
			sql := string(buf)
			sqls := splitStringChar(sql)
			for _, s := range sqls {
				util.Log().Info("buf:%v", s)
			}
		}
	}
}

func splitStringChar(s string) []string {
	a := strings.FieldsFunc(s, func(r rune) bool {
		return r == ';'
	})
	return a
}

func getSchemaHistoryVersion() string {
	var s SchemaHistory
	err := DB.Last(&s).Error
	if err != nil {
		common.Logger.Error("query error")
		return "0.0"
	}
	return s.Version
}
